package TextBookCode.unit2.unit2_2_3;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class InterceptorJdkProxy implements InvocationHandler {
    private Object target;
    private String interceptorClass = null;

    public InterceptorJdkProxy(Object target, String interceptorClass) {
        this.target = target;
        this.interceptorClass = interceptorClass;
    }

    public static Object bind(Object target, String interceptorClass) {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InterceptorJdkProxy(target, interceptorClass));
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (this.interceptorClass == null) {
            return method.invoke(this.target, args);
        } else {
            Object result = null;
            Interceptor interceptor = (Interceptor)Class.forName(this.interceptorClass).newInstance();
            if (interceptor.before(proxy, this.target, method, args)) {
                result = method.invoke(this.target, args);
            } else {
                interceptor.around(proxy, this.target, method, args);
            }

            interceptor.after(proxy, this.target, method, args);
            return result;
        }
    }
}
